<script setup lang="ts">
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
import { callTaskSendSms } from '#/api/contact/task/call';
// import { defaultFormValueGetter, useBeforeCloseDiff } from '#/utils/popup';

import { smsSchema } from '../workbench';

const emit = defineEmits<{ reload: [] }>();
const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  // layout: 'vertical',
  schema: smsSchema(),
  showDefaultActions: false,
});

// const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
//   {
//     initializedGetter: defaultFormValueGetter(formApi),
//     currentGetter: defaultFormValueGetter(formApi),
//   },
// );

const userName = ref('');
const [BasicModal, modalApi] = useVbenModal({
  fullscreenButton: false,
  // onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);

    const { name, employeeId, type, templateList } = modalApi.getData() as {
      employeeId: number | string;
      name: string;
      templateList: any[];
      type: string;
    };
    userName.value = name;
    const values = { name, employeeId, smsTemplateId: undefined };
    if (type === 'list') {
      formApi.updateSchema([
        { fieldName: 'smsTemplateId', componentProps: { all: true } },
      ]);
    }
    if (type === 'task' && templateList?.length > 0) {
      formApi.updateSchema([
        {
          fieldName: 'smsTemplateId',
          componentProps: { options: templateList },
        },
      ]);
      if (templateList.length === 1) {
        values.smsTemplateId = templateList[0].id;
      }
    }
    await formApi.setValues(values);

    // markInitialized();

    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.lock(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = cloneDeep(await formApi.getValues()) as any;
    await callTaskSendSms(data.smsTemplateId, data.employeeId);
    console.log(data);
    // resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
  }
}

async function handleClosed() {
  userName.value = '';
  await formApi.resetForm();
  // resetInitialized();
}
</script>

<template>
  <BasicModal title="发送短信" class="w-[450px]" confirm-text="确定并发送">
    <BasicForm>
      <template #name>
        <span class="text-[14px]">{{ userName }}</span>
      </template>
    </BasicForm>
  </BasicModal>
</template>
